﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Security;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace ST.Buz.Web.Controllers
{
	[Route("sys/moduleaction")]
	public class Sys_ModuleActionController : MyBaseController
	{
		private readonly IServiceSysModuleAction service;
		private readonly IServiceSysAttachment serviceSysAttachment;
		private VM_RelatedModule[] relatedModules;

		public Sys_ModuleActionController(IServiceSysModuleAction _service,
			IServiceSysAttachment _serviceSysAttachment,
			ILogger<Sys_ModuleActionController> _logger) : base(_logger)
		{
			service = _service;
			serviceSysAttachment = _serviceSysAttachment;
			relatedModules = new VM_RelatedModule[]{
				new VM_RelatedModule(){
					id="sys_attachment",
					name="相关附件",
					count=0
				}
			};
		}

		private VMS_Sys_ModuleAction GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_Sys_ModuleAction();
			vm.pnum = TextHelper.GetInt(paras, "pnum");
			vm.psize = TextHelper.GetInt(paras, "psize");
			vm.sortorder = TextHelper.GetString(paras, "sortorder");

			vm.name = TextHelper.GetString(paras, "name");
			vm.code = TextHelper.GetString(paras, "code");
			vm.moduleid = TextHelper.GetIntNullable(paras, "moduleid");
			vm.serviceid = TextHelper.GetIntNullable(paras, "serviceid");
			vm.ids = TextHelper.GetInts(paras, "ids");
			return vm;
		}

		private VMS_Sys_ModuleAction GetSearchModelFromGetRequest()
		{
			var vm = new VMS_Sys_ModuleAction();
			vm.pnum = TextHelper.GetInt(Request.Query["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Query["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Query["sortorder"]);

			vm.name = TextHelper.GetString(Request.Query["name"]);
			vm.code = TextHelper.GetString(Request.Query["code"]);
			vm.moduleid = TextHelper.GetIntNullable(Request.Query["moduleid"]);
			vm.serviceid = TextHelper.GetIntNullable(Request.Query["serviceid"]);
			vm.ids = TextHelper.GetInts(Request.Query["ids"]);
			return vm;
		}

		private VMS_Sys_ModuleAction GetSearchModelFromPostRequest()
		{
			var vm = new VMS_Sys_ModuleAction();
			vm.pnum = TextHelper.GetInt(Request.Form["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Form["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Form["sortorder"]);

			vm.name = TextHelper.GetString(Request.Form["name"]);
			vm.code = TextHelper.GetString(Request.Form["code"]);
			vm.moduleid = TextHelper.GetIntNullable(Request.Form["moduleid"]);
			vm.serviceid = TextHelper.GetIntNullable(Request.Form["serviceid"]);
			vm.ids = TextHelper.GetInts(Request.Form["ids[]"]);
			return vm;
		}

		public IActionResult Index()
		{
			return RedirectToAction("List");
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List()
		{
			ViewBag.ServiceCode = "C4A20A39BA";
			ViewBag.StateOptions = GetEnums(typeof(OrganizationState));
			//ViewBag.GenderOptions = GetEnums(typeof(Gender));
			return View();
		}

		[HttpPost("search")]
		public IActionResult Search([FromBody]JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				PageData pageData = service.GetPageList(searchModel);

				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("add")]
		public IActionResult Add()
		{
			ViewBag.ServiceCode = "C4A20A39BA";
			ViewBag.RelatedModuleActions = relatedModules;
			//ViewBag.GenderOptions = GetEnums(typeof(Gender));
			//ViewBag.RoleOptions = serviceSysRole.GetRoleSelectListItems();

			Sys_ModuleAction vm = new Sys_ModuleAction()
			{
			};
			return View("Edit", vm);
		}

		[ValidateSession]
		[HttpGet("edit/{id}")]
		[HttpGet("edit")]
		public IActionResult Edit(string id)
		{
			ViewBag.ServiceCode = "C4A20A39BA";
			ViewBag.RelatedModuleActions = relatedModules;
			//ViewBag.GenderOptions = GetEnums(typeof(Gender));
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = TextHelper.GetInt(id);
				var vm = service.GetEditDetail(rowID, sessionCurrent);

				//ViewBag.RoleOptions = serviceSysRole.GetRoleSelectListItems(vm.RolesID);

				return View(vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				return new JsonResultBase(false, "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("save")]
		public IActionResult Save([FromBody] Sys_ModuleAction model)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = service.AddOrUpdate(model, sessionCurrent);

				return new JsonResultBase(rowID);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "保存失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取指定功能信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("view/{id}")]
		[HttpGet("view")]
		public IActionResult ViewDetail(string id)
		{
			ViewBag.ServiceCode = "C4A20A39BA";
			ViewBag.RelatedModuleActions = relatedModules;
			try
			{
				int rowID = TextHelper.GetInt(id);

				UserSession sessionCurrent = GetSessionFromRequest();

				var vm = service.GetViewDetail(rowID, sessionCurrent);

				return View("View", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取指定功能信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("detail")]
		public IActionResult ViewJson([FromBody]JObject paras)
		{
			try
			{
				CheckParams();

				int id = TextHelper.GetInt(paras, "id");

				UserSession sessionCurrent = GetSessionFromRequest();
				var model = service.GetViewDetail(id, sessionCurrent);

				if (model == null)
				{
					return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
				}

				return new JsonResultBase(model);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("delete")]
		public IActionResult Delete([FromBody]JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = service.Delete(rowID, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("batchdelete")]
		public IActionResult BatchDelete([FromBody]int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				var result = service.BatchDelete(ids, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取单位编号
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("gencode")]
		public IActionResult GenCode()
		{
			try
			{
				CheckParams();
				//int id = TextHelper.GetInt(paras, "id");
				//string areaCode = TextHelper.GetString(paras, "areacode");
				UserSession sessionCurrent = GetSessionFromRequest();
				var result = service.GenCode(sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 保存排序
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("savesort")]
		public IActionResult SaveSort([FromBody]int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				var result = service.SaveSort(ids, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "保存排序失败", (int)HttpStatusCode.InternalServerError);
			}
		}
	}
}